// #include "Socket.hpp"
#include <memory>
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"
#include <fstream>

std::string GetFileContent(const std::string& path)
{
    std::ifstream in(path, std::ios::binary);
    if(!in.is_open()) return "";
    in.seekg(0, in.end);
    int filesize = in.tellg();
    in.seekg(0, in.beg);

    std::string content;
    content.resize(filesize);
    in.read((char*)content.c_str(), filesize);

    // std::vector<char> content(filesize);
    // in.read(content.data(), filesize);

    in.close();

    return content;
}
std::string SuffixToType(const std::string& suffix)
{
    if(suffix == ".html" || suffix == ".html") return "text/html";
    else if(suffix == ".png") return "image/png";
    else if(suffix == ".jpg") return "image/jpeg";
    else 
    {
        return "text/html";
    }
}
std::string HandlerRequset(std::string& request)
{
    // std::cout << request << std::endl;
    HttpRequest req;
    req.DeSerialize(request);
    req.Prase();
    req.HttpDebug();

    //读出url对应path里的内容
    std::string content;
    content = GetFileContent(req.GetPath());
    std::cout << "content: " << content << std::endl;
    if(!content.empty())
    {
        std::string httpstatusline = "Http/1.0 200 OK\r\n";
        std::string httpheader = "Content-Length: " + std::to_string(content.size()) + "\r\n";
        httpheader += "Content-Type: " + SuffixToType(req.GetSuffix()) + "\r\n"; // 正文的类型
        httpheader += "\r\n";
        std::string httpresponse = httpstatusline + httpheader + content;
        // request = httpstatusline + httpheader + content;
        return httpresponse;
    }
    return "";
}
int main(int argc, char* argv[])
{
    uint16_t port = std::stoi(argv[1]);

    std::unique_ptr<TcpServer> tsvr = std::make_unique<TcpServer>(port, HandlerRequset);
    
    tsvr->loop();
}